﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Jungle.Code.Core;
using Jungle.Code.Utils;
using Jungle.Code.DAL;
using System.Collections.Generic;
using Jungle.Admin.Controls.Templates;

namespace Jungle.Admin.Controls
{
    public partial class ContentManager : System.Web.UI.UserControl
    {
        int nodeID;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["nodeID"] != null)
            {
                nodeID = int.Parse(Request["nodeID"]);
                BindDataForEdit(nodeID);
                GetFullLink();
 
            }
            Node activeNode = new Node();
            activeNode = Node.GetByNodeID(nodeID);

            if (activeNode.ParentNodeID == 0) delNode.Visible = false;

            Template template = new Template();
            template = Template.GetByTemplateID(activeNode.TemplateID);


            string virtualPath = UrlHelper.GetApplicationPath() + template.BasePath + "/" + template.AdminTemplate;
            Control templateControl = new Control();
            templateControl = base.LoadControl(virtualPath);
            templateHolder.Controls.Add(templateControl);

            List<Section> sectList = new List<Section>();
            sectList = Section.GetByNodeID(nodeID);

            Hashtable containers = new Hashtable();
            foreach (Control value in templateControl.Controls)
            {
                if (value is PlaceHolder)
                {
                    Label name = new Label();
                    name.Text = "<div class=\"cont-t\">Контейнер <b>" + value.ID + "</b></div>";
                    value.Controls.Add(name);
                    containers.Add(value.ID, value);
                }
            }
            foreach (Section sect in sectList)
            {
                if (containers.ContainsKey(sect.Container))
                {
                    PlaceHolder holder = (PlaceHolder)containers[sect.Container];
                    Module module = new Module();
                    module = Module.GetByModuleID(sect.ModuleID);
                    holder.Controls.Add(this.GetBlock(module, sect));
                }
            }

            if (!this.IsPostBack)
            {
                ddlModules.DataSource = Module.GetAll();
                ddlModules.DataTextField = "Name";
                ddlModules.DataValueField = "ModuleID";
                ddlModules.DataBind();

                ddlContainers.DataSource = containers.Keys;
                ddlContainers.DataBind();
            }

        }
        public Control GetBlock(Module mod, Section sec)
        {
            Control ctrl = Page.LoadControl("Controls/Templates/Block.ascx");
            Block bl = ((Block)ctrl);
            bl._Title.Text = mod.Name;
            if (sec.Ord == 1)
                bl._OrderUp.Visible = false;

            switch (mod.Group)
            {
                case 1:
                    bl._Title.NavigateUrl = "";
                    break;
                case 2:
                    bl._Title.NavigateUrl = UrlHelper.FormatUrl("Default.aspx",
                                            new Arg("nodeID", nodeID.ToString()),
                                            new Arg("sectionID", sec.SectionID.ToString()),
                                            new Arg("cmd", "mod"));
                    break;
                case 3:
                    bl._Title.NavigateUrl = "";
                    break;
                case 4:
                    bl._Title.NavigateUrl = UrlHelper.FormatUrl("Default.aspx",
                        new Arg("nodeID", nodeID.ToString()),
                        new Arg("sectionID", sec.SectionID.ToString()),
                        new Arg("cmd", "mod"));
                    break;
            }

            if (sec.Enabled)
                bl._Enabled.Text = "вкл";
            else
            {
                bl._Enabled.Text = "выкл";
                bl._Enabled.CssClass = "off";
            }

            bl._Delete.CommandName = sec.SectionID.ToString();
            bl._Delete.Click += new EventHandler(DeleteClick);

            bl._Enabled.CommandName = sec.SectionID.ToString();
            bl._Enabled.CommandArgument = (!sec.Enabled).ToString();
            bl._Enabled.Click += new EventHandler(EnabledClick);


            bl._Prop.Visible = false;

            return ctrl;
        }
        void EnabledClick(object sender, EventArgs e)
        {
            LinkButton btn = (LinkButton)sender;
            int sectionID = int.Parse(btn.CommandName);
            bool enabled = bool.Parse(btn.CommandArgument);
            Section.SetEnabledBySectionID(sectionID, enabled);
            Response.Redirect(Request.Url.ToString());
        }
        void DeleteClick(object sender, EventArgs e)
        {
            LinkButton btn = (LinkButton)sender;
            int sectionID = int.Parse(btn.CommandName);
            Section.DeleteBySectionID(sectionID);
            Response.Redirect(Request.Url.ToString());
        }
        protected void InsertClick(object sender, EventArgs e)
        {
            Section sect = new Section();
            sect.Ord = 0;
            sect.Container = ddlContainers.SelectedValue;
            sect.ModuleID = int.Parse(ddlModules.SelectedValue);
            sect.NodeID = nodeID;
            sect.Enabled = true;
            Section.Insert(sect);
            Response.Redirect(Request.Url.ToString());
        }

        protected void DeleteNode(object sender, EventArgs e) 
        {
            if(Request["nodeID"] != null)
            {
                SqlConnection connect = new SqlConnection(DBHelper.ConnectionString);
                SqlCommand command = new SqlCommand("crNodes_DeleteNodeByID", connect);
                command.CommandType = CommandType.StoredProcedure;
                
                SqlParameter param_id_node = command.Parameters.Add("@id_node", SqlDbType.Int);
                param_id_node.Value = Request["nodeID"];

                command.Connection.Open();
                    command.ExecuteNonQuery();
                command.Connection.Close();

                Response.Redirect("~/Admin/Default.aspx?nodeID=1&cmd=cont");
            }
        }

        protected void UpdateTemplate(object sender, EventArgs e)
        {
            if (Request["nodeID"] != null)
            {
                SqlConnection connect = new SqlConnection(DBHelper.ConnectionString);
                SqlCommand command = new SqlCommand("crNodes_UpdateTemplate", connect);
                command.CommandType = CommandType.StoredProcedure;

                SqlParameter param_templateID = command.Parameters.Add("@templateID", SqlDbType.Int);
                SqlParameter param_nodeID = command.Parameters.Add("@nodeID", SqlDbType.Int);

                param_templateID.Value = ddlTemplateID.SelectedValue;
                param_nodeID.Value = Request["nodeID"];

                command.Connection.Open();
                    command.ExecuteNonQuery();
                command.Connection.Close();

                Response.Redirect(Request.Url.ToString());
            }
        }

        protected void BindDataForEdit(int nodeID)
        {
            Node node = new Node();
            node = Node.GetByNodeID(nodeID);
            BindDefaultData(node);
            ddlTemplateID.Items.FindByValue(node.TemplateID.ToString()).Selected = true;

        }

        protected void BindDefaultData(Node node)
        {
            Node topNode = new Node();
            topNode = Node.GetTopByLangID(node.LangID);
            ddlTemplateID.DataSource = Template.GetAll();
            ddlTemplateID.DataBind();
        }

        protected void GetFullLink()
        {
            if (Request["nodeID"] != null)
            {
                string fLink;
                using (SqlConnection connect = new SqlConnection(DBHelper.ConnectionString))
                {
                    SqlCommand command = new SqlCommand("crNodes_GetRelativeUrlByID", connect);
                    SqlDataReader reader = null;
                    command.CommandType = CommandType.StoredProcedure;

                    SqlParameter param_nodeID = command.Parameters.Add("@nodeID", SqlDbType.Int);

                    param_nodeID.Value = Request["nodeID"];

                    command.Connection.Open();
                    reader = command.ExecuteReader();
                    reader.Read();
                        if(reader.GetValue(0).ToString().Length == 2)
                        fLink = UrlHelper.GetSiteUrl() + "/" + reader.GetValue(0).ToString() + "/main.aspx";
                        else
                        fLink = UrlHelper.GetSiteUrl() + "/" + reader.GetValue(0).ToString() + ".aspx";
                    command.Connection.Close();
                }
               FullLink.NavigateUrl = fLink;
               FullLink.Text = fLink;
            }
            
        }
    }
}